package com.shqcjd.yunweiyanoperator.ui.activity.mine;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.model.pojo.DepartmentBean;
import com.shqcjd.yunweiyanoperator.ui.adapter.DepartmentSelectAdapter;
import com.shqcjd.yunweiyanoperator.ui.base.BaseActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.Config;
import com.shqcjd.yunweiyanoperator.util.SpacesItemDecoration;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shqcjd.yunweiyanoperator.util.UIUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 专业列表
 */
public class SpecialtyListActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener {

    private static final int PAGE_SIZE = Config.PAGE_TOTAL;
    private int mNextRequestPage = 1;

    @BindView(R.id.btn_finish)
    ImageView btnFinish;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    private View notDataView;
    private DepartmentSelectAdapter departmentAdapter;
    private Context mContext;
    private final int SELECT_SPECIALTY = 12110;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_specialty_list;
    }


    @OnClick(R.id.btn_finish)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void initView() {
        tvTitle.setText("选择专业");
        mContext = this;

        notDataView = getLayoutInflater().inflate(R.layout.layout_no_data, (ViewGroup) rvList.getParent(), false);
        initRefreshLayout();
        departmentAdapter = new DepartmentSelectAdapter();
        rvList.setLayoutManager(new LinearLayoutManager(this));
        rvList.addItemDecoration(new SpacesItemDecoration(0, UIUtils.dip2px(1)));
        rvList.setAdapter(departmentAdapter);
        departmentAdapter.setOnLoadMoreListener(this,rvList);
        departmentAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                DepartmentBean.ListBean item = (DepartmentBean.ListBean) adapter.getItem(position);
                Intent intent = new Intent();
                intent.putExtra("specialtyName", item.departmentName);
                intent.putExtra("specialtyId", item.departmentId);
                setResult(SELECT_SPECIALTY, intent);
                finish();
            }
        });
    }

    private void initRefreshLayout() {
        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        swipeLayout.setRefreshing(true);
    }

    @Override
    public void initData() {
        refresh();
    }

    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }

    private void refresh() {
        mNextRequestPage = 1;
        departmentAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        Map<String, String> map = new HashMap<>();
        map.put("page", mNextRequestPage+"");
        map.put("size", PAGE_SIZE+"");
        ApiService.departmentList(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<DepartmentBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        swipeLayout.setRefreshing(true);
                    }
                    @Override
                    public void _onNext(ResponseData<DepartmentBean> retData) {
                        if (retData.retCode == 10000) {
                            setData(true, retData.data.list);
                        } else {
                            ToastUtils.showShort(mContext,retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext,errorMessage);
                        departmentAdapter.setEnableLoadMore(true);
                        swipeLayout.setRefreshing(false);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        departmentAdapter.setEnableLoadMore(true);
                        swipeLayout.setRefreshing(false);
                    }
                });
    }

    private void loadMore() {
        Map<String, String> map = new HashMap<>();
        map.put("page", mNextRequestPage+"");
        map.put("size", PAGE_SIZE+"");
        ApiService.departmentList(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<DepartmentBean>>() {
                    @Override
                    public void _onNext(ResponseData<DepartmentBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            boolean isRefresh =mNextRequestPage ==1;
                            setData(isRefresh, retData.data.list);
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                        departmentAdapter.loadMoreFail();
                    }

                });
    }

    private void setData(boolean isRefresh, List data) {

        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            if (size > 0) {
                departmentAdapter.setNewData(data);
            } else {
                departmentAdapter.setNewData(null);
                departmentAdapter.setEmptyView(notDataView);
            }
        } else {
            if (size > 0) {
                departmentAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            departmentAdapter.loadMoreEnd(isRefresh);
        } else {
            departmentAdapter.loadMoreComplete();
        }
    }
}
